package cc.fs.video.myvideoproject.ui.fragment

import android.app.Fragment
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cc.fs.video.myvideoproject.AppContext
import cc.fs.video.myvideoproject.R
import cc.fs.video.myvideoproject.beans.VideoBean
import cc.fs.video.myvideoproject.ui.VideoActivity
import cc.fs.video.myvideoproject.ui.adapter.VideoAdapter
import cc.fs.video.myvideoproject.utils.bindView
import tv.danmaku.ijk.media.player.IjkMediaPlayer
import java.io.File
import java.util.*

/**
 * Created by fostion on 2015/10/13.
 */
class VideoFragment : Fragment() {

    val videos: ArrayList<VideoBean> = ArrayList()
    val recycleview: RecyclerView by bindView(R.id.recycleview)
    var adapter: VideoAdapter ? = null


    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater?.inflate(R.layout.fragment_video, container, false)
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        adapter = VideoAdapter(videos)
        recycleview.layoutManager = LinearLayoutManager(activity)
        recycleview.adapter = adapter
        adapter?.onClick = {
            video ->
            VideoActivity.start(activity, video)
        }
    }

    fun setFile(path: String) {
        videos.clear()
        val file = File(path)
        val files = file.listFiles()
        for (video in files) {
            if (!video.isDirectory && isVideo(video.name)) {
                var videoBean = AppContext.findVideo(video.path)
                if (videoBean != null) {
                    videos.add(videoBean)
                } else {
                    val ijkplayer = IjkMediaPlayer()
                    ijkplayer.dataSource = video.path
                    ijkplayer.prepareAsync()
                    videoBean = VideoBean()
                    videoBean.title = video.name
                    videoBean.path = video.absolutePath
                    videoBean.size = video.totalSpace
                    videoBean.duration = 0
                    ijkplayer.stop()
                    videos.add(videoBean)
                }
            }
        }
        adapter?.notifyDataSetChanged()
    }

    fun isVideo(_name: String): Boolean {
        var name = _name.toLowerCase()
        if (name.endsWith(".mp4") || name.endsWith(".avi") || name.endsWith(".mov") || name.endsWith(".asf") || name.endsWith(".wmv") || name.endsWith(".3gp") || name.endsWith(".mkv") || name.endsWith(".flv")) {
            return true
        }
        return false
    }


}